<!-- eslint-disable vue/valid-v-for -->
<!-- eslint-disable vue/no-parsing-error -->
<template>
  <div>
    <!--上方搜索框-->
    <el-form :inline="true" :model="keyword" ref="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-button type="danger" size="small" @click="deleteBatch" icon="el-icon-delete">删除</el-button>
        <el-button type="warning" size="small" @click="openAddDialog" icon="el-icon-plus">添加</el-button>
      </el-form-item>
      <el-form-item label="单位编码" prop="measureCode">
        <el-input size="small" clearable v-model="keyword.measureCode" placeholder="单位编码"></el-input>
      </el-form-item>
      <el-form-item label="单位名称" prop="measureName">
        <el-input size="small" clearable v-model="keyword.measureName" placeholder="单位名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="search" icon="el-icon-search">查询</el-button>
        <el-button type="primary" plain size="small" @click="resetSearchForm('searchForm')" icon="el-icon-refresh">
          重置
        </el-button>
        <el-button type="primary" plain size="small" @click="dialogExcelVisible = true" icon="el-icon-upload2">导入
        </el-button>
        <el-button type="primary" plain size="small" @click="downloadExcel" icon="el-icon-download">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 上传excel的对话框 -->
    <el-dialog title="上传计量单位Excel" :visible.sync="dialogExcelVisible" width="40%">
      <el-upload

class="upload-demo"
drag
action="http://localhost:8888/md/unit/upload/excel"
accept=".xlsx,.xls"
        :on-success="uploadExcelSuccess"
:on-error="uploadExcelError"
multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传.xlsx,.xls文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>

    <!--添加/更新对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="unitMeasure" :rules="unitMeasureRules" ref="unitMeasureRulesForm">
        <el-form-item label="单位编码" prop="measureCode">
          <el-input v-model="unitMeasure.measureCode" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="单位名称" prop="measureName">
          <el-input v-model="unitMeasure.measureName" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="是否是主单位" prop="primaryFlag">
          <el-radio-group v-model="unitMeasure.primaryFlag" @input="setPrimary" @change="handleRadioChange"> 
            <!--标签中间的是,对外展现的,label中的Y是表单数据,发给后端的-->
            <el-radio label="Y" >是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="isShowPrimary">
          <el-form-item label="主单位">
            <el-select v-model="unitMeasure.primaryId" placeholder="请选择主单位">
              <el-option v-for="primaryUnit in primaryUnitList" :key="primaryUnit.measureId" 
              :label="primaryUnit.measureName" :value="primaryUnit.measureId" />

            </el-select>
          </el-form-item>
          <el-form-item label="与主单位换算比例">
            <el-input-number v-model="unitMeasure.changeRate" label="换算比例"></el-input-number>
          </el-form-item>
        </div>
        <el-form-item label="是否启用" prop="enableFlag">
          <el-radio-group v-model="unitMeasure.enableFlag">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="unitMeasure.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUnitMeasure('unitMeasureRulesForm')">确 定</el-button>
      </div>
    </el-dialog>
 
    <!--中间表格区域-->
    <el-table v-loading="loading" :data="measureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单位编码" align="center" prop="measureCode" />
      <el-table-column label="单位名称" align="center" prop="measureName" />
      <el-table-column label="是否是主单位" align="center" prop="primaryFlag">
        <template slot-scope="scope">
          <el-tag :type="scope.row.primaryFlag == 'Y' ? '' : 'danger'">
            <span>{{ scope.row.primaryFlag == 'Y' ? '是' : '否' }}</span></el-tag>
        </template>
      </el-table-column>

      <el-table-column label="与主单位换算比例" align="center" prop="changeRate">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.changeRate).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="enableFlag">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enableFlag == 'Y' ? '' : 'danger'">
            <span>{{ scope.row.enableFlag == 'Y' ? '是' : '否' }}</span></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--下方分页区域-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"/>
  </div>
</template>

<script>
import { getList, addMeasure, mdUnitInfo, updateMeasure,findPrimaryUnit,delById,delBatch} from '@/api/unit'

export default {
  name: 'Unit',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 单位表格数据
      measureList: [],
      // 存储主单位数据
      primaryUnitList: [],
      pageNum: 1,
      pageSize: 5,
      currentPage: 1,
      total: 0,
      keyword: {
        measureCode: null,
        measureName: null
      },
      ids: [],
      title: '',
      dialogFormVisible: false,
      dialogExcelVisible: false,
      unitMeasure: {
        measureCode: null,
        measureName: null,
        primaryFlag: null,
        enableFlag: null,
        remark: null,
        primaryId: null,
        measureId: null,
        changeRate: null
      },
      unitMeasureRules: {
        measureCode: [
          { required: true, message: '单位编码不能为空', trigger: 'blur' }
        ],
        measureName: [
          { required: true, message: '单位名称不能为空', trigger: 'blur' }
        ],
        primaryFlag: [
          { required: true, message: '是否是主单位不能为空', trigger: 'blur' }
        ],
        enableFlag: [
          { required: true, message: '是否默认启用不能为空', trigger: 'blur' }
        ]
      },
      isShowPrimary: false
    }
  },
  methods: {
    fetchData() { // 获取数据
      // 分页 + 模糊查询 带到后端的参数
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        measureCode: this.keyword.measureCode,
        measureName: this.keyword.measureName
      }
      // axios.get(url, params).then(res => {}
      getList(params).then(res => {
        console.log(' res ', res)
        const pageInfo = res.data // {total:100,dataList:[]}
        // console.log("pageInfo",pageInfo)
        this.loading = false
        this.measureList = pageInfo.dataList
        this.total = pageInfo.total
      })
    },
    // 多选框选中数据
    handleSelectionChange(selectionRowArr) {
      this.ids = []
      // console.log(selectionRowArr)
      for (let i = 0; i < selectionRowArr .length; i++) {
        this.ids.push(selectionRowArr[i].measureId)
      }
      // console.log("ids",this.ids)
    },
    // 页面大小改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 当前页码改变时触发
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
    },
    // 模糊搜索
    search() {
      this.fetchData()
    },
    // 重置表单
    resetSearchForm(formName) {
      this.$refs[formName].resetFields()
      this.fetchData()
    },
    // 根据id删除
    handleDelete(row) {
      // console.log(row.measureId)
      this.$confirm('是否确认删除单位编号为' + row.measureId + '的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       
        // eslint-disable-next-line no-undef
        delById(row.measureId).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 批量删除
    deleteBatch() {
      this.$confirm('是否确认删除单位编号为[' + this.ids + ']的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idStr = this.ids.join(',')
        console.log(idStr)

        // console.log("idStr",idStr)
        let params = {
          ids: this.ids.join(',')
        }
        // eslint-disable-next-line no-undef
        delBatch(this.ids).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开添加对话框
    openAddDialog() {
      this.title = '添加'
      this.dialogFormVisible = true// dialogFormVisible为true时,dialogForm显示
    },
    // 打开修改对话框
    handleUpdate(row) {
      this.title = '修改'
      this.dialogFormVisible = true
      // 回填数据，从后端id查询一条数据，其实没有必要，因为row就是当前行的数据
      mdUnitInfo({ id: row.measureId }).then(res => {
        // 取到res之后进行回显
        console.log('305:res', res)
        this.unitMeasure = res.data
      })
    },
    // 添加非主单位时,查询主单位
    setPrimary() {
      // eslint-disable-next-line eqeqeq
      if (this.unitMeasure.primaryFlag == 'N') {
        this.isShowPrimary = true
        // eslint-disable-next-line no-undef
        // findPrimaryUnit().then(res => {
        //   this.primaryUnitList = res.data
        // })
      }
    },
    handleRadioChange() {
      console.log('316hang ：', this.unitMeasure.primaryFlag)
      if (this.unitMeasure.primaryFlag == 'Y') {
        this.isShowPrimary = false
      } else {
        this.isShowPrimary = true
        //axios请求主单位数据
        findPrimaryUnit().then(res => {
          this.primaryUnitList = res.data;
        })
      }
    },
    // 添加计量单位
    addUnitMeasure(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.title == '添加'){
      
          // addMeasuree需要在当前页面引入,否则会报错
            
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.fetchData()// 刷新页面
          addMeasure(this.unitMeasure).then(res => {
            this.$refs[formName].resetFields()
          })
          }else if(this.title == '修改'){
              //此处执行修改...
              console.log("修改332",this.unitMeasure)
              updateMeasure(this.unitMeasure).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.fetchData()// 刷新页面
                this.dialogFormVisible = false;
          })
          }
          
        } else {
          console.log('error submit!!')
          return false
        }
          // 此处执行添加...
        this.dialogFormVisible = false
      })
    },
    uploadExcelSuccess() {
      this.$message({
        message: '上传成功'
      })
      this.dialogExcelVisible = false
      this.fetchData()
    },
    uploadExcelError(err) {
      this.$message({
        type: 'error',
        message: err
      })
    },
    downloadExcel() {
      type: 'success',
      this.$confirm('确定要导出数据吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 方案1: 原生js方式发起导出excel请求,后端设置响应格式
        window.location.href = 'http://localhost:8888/md/unit/download/excel'
        // 方案1的话后端需要设置响应格式和内容
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出数据！'
        })
      })
    }
  },
  // 生命周期钩子函数(vue对象创建完,自动调用该方法)
  created() {
    this.fetchData()
  }
}
</script>

<style scoped></style>
